package com.yingside.gui.lovo;

import com.lovo.netCRM.component.LovoButton;
import com.lovo.netCRM.component.LovoTable;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

public class TestLovoTable extends JFrame {
    //Lovo封装的这些Swing控件，默认都是放在自定义布局管理器里面的
    //setLayout(null),所以创建对象之后，需要设置位置和大小
    private LovoTable table;

    private JPanel panel;

    private LovoButton btnDel,btnQuery,btnEdit;

    public TestLovoTable(){
        this.setTitle("LovoTable窗口");
        this.setBounds(300, 300, 400, 400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panel = new JPanel();
        panel.setLayout(null);

        //LovoTable默认有4个参数
        //1、表示这个控件放在哪个容器中
        //2、表示表头的数组
        //3、表示要放入到表格中数据的泛型的属性名,其实就是和table绑定集合的泛型属性对应
        //4、表示这个对象的主键属性(和后面学习的数据库对应，对于现在来说就是对象的id属性)
        table = new LovoTable(panel,
                new String[]{"序号","书名","作者","价格"},
                new String[]{"id","bookName","author","price"},
                "id");

        List<Book> bookList = new ArrayList<>();

        Book b1 = new Book(1,"斗破苍穹","天蚕土豆",30.5);
        Book b2 = new Book(2,"斗罗大陆","唐家三少",31.5);
        Book b3 = new Book(3,"霸道总裁爱上我","丽丽",32.5);
        Book b4 = new Book(4,"凡人修仙传","耳根",34.5);
        Book b5 = new Book(5,"家有娇妻","漂亮女孩",12);
        bookList.add(b1);
        bookList.add(b2);
        bookList.add(b3);
        bookList.add(b4);
        bookList.add(b5);

        //将集合数据绑定到table中
        table.updateLovoTable(bookList);

        //设置表格的位置和大小
        table.setSizeAndLocation(0,0,400,200);

        btnDel = new LovoButton("删除",50,250,panel);
        btnQuery = new LovoButton("查询",170,250,panel);
        btnEdit = new LovoButton("修改",290,250,panel);

        btnDel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int key = table.getKey();
                System.out.println("key = " + key);
                Book b = null;
                for (int i=0; i<bookList.size(); i++){
                    if(key == bookList.get(i).getId()){
                        b = bookList.get(i);
                        break;
                    }
                }

                int n = JOptionPane.showConfirmDialog(null,"你确定要删除吗?");
                if(n == 0){
                    bookList.remove(b);
                    //删除成功之后，界面table重新绑定集合
                    table.updateLovoTable(bookList);
                }

            }
        });

        this.add(panel);

    }

    public static void main(String[] args) {
        TestLovoTable lovoTable = new TestLovoTable();
        lovoTable.setVisible(true);
    }
}
